package zy.service.report.excel.config;

import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

public class MapWriter extends AbstractFormatWriter<Map<String, Object>> {
	public void writeTitle(Sheet sheet, String title, String[] label, String[] name, List<Map<String, Object>> data) {
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, label.length - 1));
		Row row = sheet.createRow(0);
		Cell titleCell = row.createCell(0);
		titleCell.setCellType(CellType.STRING);
		titleCell.setCellValue(title);
	}

	public void writeHead(Sheet sheet, String title, String[] label, String[] name, List<Map<String, Object>> data) {
		Row headRow = sheet.createRow(1);
		int length = label.length;
		for (int j = 0; j < length; j++) {
			Cell tempCell = headRow.createCell(j);
			tempCell.setCellType(CellType.STRING);
			tempCell.setCellValue(label[j]);
		}
	}

	public void writeData(Sheet sheet, String title, String[] label, String[] name, List<Map<String, Object>> data) {
		int size = data.size();
		for (int j = 0; j < size; j++) {
			Row dataRow = sheet.createRow(2 + j);
			Map<String, Object> rowData = data.get(j);

			boolean _defaultRowCallback = true;
			for (RowCallback<Map<String, Object>> rowCallback : rowCallbacks) {
				if (rowCallback.canProcess(j, rowData, dataRow)) {
					rowCallback.process(j, rowData, dataRow);
					_defaultRowCallback = false;
					break;
				}
			}

			if (_defaultRowCallback) {
				int column = name.length;
				for (int k = 0; k < column; k++) {
					Cell tempCell = dataRow.createCell(k);
					String columnName = name[k];
					Object value = rowData.get(columnName);

					boolean _defaultColumnCallback = true;
					for (ColumnCallback<Map<String, Object>> columnCallback : columnCallbacks) {
						if (columnCallback.canProcess(j, rowData, dataRow, k, value, columnName, tempCell)) {
							columnCallback.process(j, rowData, dataRow, k, value, columnName, tempCell);
							_defaultColumnCallback = false;
							break;
						}
					}

					if (_defaultColumnCallback) {
						if (value != null) {
							tempCell.setCellType(CellType.STRING);
							tempCell.setCellValue(value.toString());
						}
					}
				}
			}
		}
	}
}